package com.nx.platform.es.bean.modle.query;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.nx.platform.es.common.utils.MoreMaps;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author
 * @since 2016年10月15日
 */
public class StringMatchParser implements QueryFieldConfigParser {

    private static final Pattern FORMAT_FACE = Pattern.compile("[\\w.]++");
    private static final Pattern FORMAT_FIELDNAME = Pattern.compile("[\\w.]++(?:\\^\\d++)?+");

    @Override
    public ImmutableMap<String, ?> parse(Map<?, ?> settings) {
        //
        String face = MoreMaps.getString(settings, "face", "");
        String fieldName = MoreMaps.getString(settings, "fieldName", "");
        if ("".equals(fieldName)) {
            fieldName = face;
        }
        Preconditions.checkState(FORMAT_FACE.matcher(face).matches(), "param face empty or incorrect: " + face);
        Preconditions.checkState(FORMAT_FIELDNAME.matcher(fieldName).matches(),
                "param fieldName empty or incorrect: " + fieldName);
        //
        String _type = MoreMaps.getString(settings, "_type", "");
        String _operator = MoreMaps.getString(settings, "_operator", "");
        String _minimum_should_match = MoreMaps.getString(settings, "_minimum_should_match", "");
        String _analyzer = MoreMaps.getString(settings, "_analyzer", "");
        Integer alternatives = MoreMaps.getInteger(settings, "_alternatives", 8);
        Preconditions.checkState(alternatives < 16 && alternatives > 1, "param alternatives incorrect");
        //
        ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
        builder.put("face", face);
        builder.put("fieldName", fieldName);
        builder.put("_type", _type);
        builder.put("_operator", _operator);
        builder.put("_minimum_should_match", _minimum_should_match);
        builder.put("_analyzer", _analyzer);
        builder.put("_alternatives", alternatives);
        return builder.build();
    }

}
